<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 后台主控制器
 *
 * @author      Eden
 * @datetime    2016/11/24 21:41
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class ADM_Controller extends CI_Controller
{
    // 后台模板主目录
    const TMP_DIR = 'admin';

    public $role = 'admin';
    public $detail = [];
    public $baseId = 0;

    public function __construct()
    {
        parent::__construct();
        $this->_checkACL();
        $role = $this->session->userdata('role');
        if (!empty($role)) {
            $this->role = $role;
            $this->baseId = $this->session->userdata('baseId');
        }
        $this->detail = $this->session->userdata('adminDetail');
    }

    public function _checkACL()
    {
        if (!$this->session->has_userdata('adminDetail')) {
            redirect('/login');
            exit;
        }
    }

    public function getMenu()
    {
        $role = $this->session->userdata('role');
        $menus = $this->$role();
        return $menus;
    }

    function getAllMenus()
    {
        $this->config->load('menu');

        $query = $this->db->order_by('id', 'ASC')->get('menu');
        $menus = $query->result_array();
        if (empty($menus)) {
            return [];
        }

        $mainRoles = [];
        $subMenus = [];
        foreach ($menus as $item) {
            if ($item['pid'] == 0) {
                $mainRoles[$item['id']] = [
                    'id' => intval($item['id']),
                    'pid' => 0,
                    'controller' => $item['controller'],
                    'name' => $item['name'],
                    'url' => $item['url'],
                    'icon' => $item['icon'],
                    'level' => intval($item['level']),
                    'subMenu' => []
                ];
            } else {
                if (!isset($subMenus[$item['pid']])) {
                    $subMenus[$item['pid']] = [];
                }
                $subMenus[$item['pid']] = array_merge($subMenus[$item['pid']], [[
                    'id' => intval($item['id']),
                    'pid' => intval($item['pid']),
                    'url' => $item['url'],
                    'controller' => $item['controller'],
                    'title' => $item['name'],
                    'level' => intval($item['level'])
                ]]);
            }
        }

        foreach ($mainRoles as $key => &$role) {
            $role['subMenu'] = isset($subMenus[$key]) ? $subMenus[$key] : [];
        }

        return $mainRoles;
        // return $config = $this->config->item('menu');
    }

    function admin()
    {
        $roleId = $this->detail['roleId'];
        if (empty($roleId)) {
            redirect('/login');die;
        }

        if ($roleId == 1) {
            // all
            $roles = null;
        } else {
            // get roleinfo
            $q = $this->db->where('id', $roleId)->get('admin_role');
            $item = $q->row_array();
            $roles = json_decode($item['value'], true);
        }

        return $this->formatMenu($roles);
    }

    function formatMenu($roles)
    {
        $allRoles = $this->getAllMenus();
        $return = [];
        foreach($allRoles as $item) {
            if (empty($roles) || in_array($item['id'], $roles)) {
                $return[$item['controller']] = [
                    'name' => $item['name'],
                    'icon' => $item['icon'],
                    'url' => $item['url'],  // todo
                    'subMenu' => []
                ];
            } else {
                if (!empty($item['subMenu'])) foreach ($item['subMenu'] as $v) {
                    if (in_array($v['id'], $roles)) {
                        $return[$item['controller']] = [
                            'name' => $item['name'],
                            'icon' => $item['icon'],
                            'url' => $item['url'],  // todo
                            'subMenu' => []
                        ];
                        break;
                    }
                }
            }

            if (!empty($return[$item['controller']])) {
                $subMenus = [];
                foreach ($item['subMenu'] as $v) {
                    if (empty($roles) || in_array($v['id'], $roles)) {
                        $subMenus[] = [
                            'title' => $v['title'],
                            'controller' => $v['controller']
                        ];
                    }
                }
                $return[$item['controller']]['subMenu'] = $subMenus;
            }
        }

        return $return;
    }

    /**
     * 基地菜单
     * @return array
     */
    public function base()
    {
        return array(
            'system' => array(
                'name' => '系统设置',
                'url' => '',
                'icon' => 'fa-gear',
                'subMenu' => array(
                    array(
                        'title' => '管理员',
                        'controller' => 'admin'
                    ),
                    array(
                        'title' => '基地管理',
                        'controller' => 'base'
                    )
                ),
            ),
            'goods' => array(
                'name' => '商品管理',
                'url' => '',
                'icon' => 'fa-shopping-cart',
                'subMenu' => array(
                    array(
                        'title' => '产品列表',
                        'controller' => 'lists'
                    ),
                    array(
                        'title' => '模板设置',
                        'controller' => 'express'
                    )
                )
            ),
            'order' => array(
                'name' => '订单管理',
                'url' => 'order/lists/index',
                'icon' => 'fa-th-list',
                'subMenu' => array()
            ),
            'money' => array(
                'name' => '账务管理',
                'url' => '',
                'icon' => 'fa-credit-card',
                'subMenu' => array(
                    array(
                        'title' => '供应商对账',
                        'controller' => 'purchaser'
                    ),
                    array(
                        'title' => '历史对账单',
                        'controller' => 'history'
                    ),
                    array(
                        'title' => '银行信息',
                        'controller' => 'bank'
                    )
                )
            ),

        );
    }

    /**
     * @return mixed
     */
    public function allMenus()
    {
        $query = $this->db->get('menu');
        return $query->result_array();
    }
}
